package com.mystnihon.freeremote.util;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class Snippets {
    private static final int CONNECT_LOGIN_FAILED = -1;
    private static final String TAG = null;
    private static final int CONNECT_NOT_CONNECTED = 0;
    private static final int CONNECT_CONNECTED = 0;
    private static String serverUrl;
    private static String assistanceUrl;

    private static int connectionStatus;
    private static String id;
    private static String idt;

    // En cas de résussite : http://adsl.free.fr/compte/console.pl?id=417389&idt=10eb38933107f10c
    // En cas d'erreur de login/pass : /login/login.pl?login=0909090909&error=1
    /**
     * connectionFree : identifie sur le portail de Free avec le login/pass demandé
     * 
     * @param l : login (identifiant = numéro de téléphone Freebox)
     * @param p : password (mot de passe Freebox)
     * @return CONNECT_CONNECTED || CONNECT_NOT_CONNECTED || CONNECT_LOGIN_FAILED
     */
    private static int connectionFree(String l, String p, boolean assistance) {
        String m_id = null;
        String m_idt = null;
        HttpURLConnection h = null;

        if (l == null) {
            return CONNECT_LOGIN_FAILED;
        }

        Log.d(TAG, "Connect Free start ");
        try {
            List<NameValuePair> listParameter = new ArrayList<NameValuePair>();
            listParameter.add(new BasicNameValuePair("login", l));
            listParameter.add(new BasicNameValuePair("pass", p));

            if (!assistance)
                h = prepareConnection(serverUrl, "POST");
            else
                h = prepareConnection(assistanceUrl, "POST");
            h.setDoOutput(true);
            OutputStreamWriter o = new OutputStreamWriter(h.getOutputStream());
            // o.write(makeStringForPost(listParameter, false, null));
            o.flush();
            o.close();
            if (h.getHeaderFields().get("location") != null) {
                String s = h.getHeaderFields().get("location").toString();
                Log.d(TAG, "connectFree : " + s);
                String priv;
                if (s.indexOf("idt=") > -1) {
                    priv = s.substring(s.indexOf("idt=") + 4);
                    if (priv.indexOf("]") > -1) {
                        priv = priv.substring(0, priv.indexOf(']'));
                    }
                    m_idt = priv;
                    Log.d(TAG, "idt :" + priv);
                    priv = s.substring(s.indexOf("?id=") + 4);
                    priv = priv.substring(0, priv.indexOf('&'));
                    m_id = priv;
                    Log.d(TAG, "id :" + priv);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (!assistance) {
                connectionStatus = CONNECT_NOT_CONNECTED;
                id = null;
                idt = null;
            }
            return connectionStatus;
        } finally {
            /*
             * if (h != null) { h.disconnect(); }
             */}
        if (!assistance) {
            if (m_id != null && m_idt != null) {
                connectionStatus = CONNECT_CONNECTED;
                id = m_id;
                idt = m_idt;
            } else {
                Log.d(TAG, "MonCompeFree : AUTHENTIFICATION FAILED !");
                connectionStatus = CONNECT_LOGIN_FAILED;
                id = null;
                idt = null;
            }
        }
        return connectionStatus;
    }

    private static HttpURLConnection prepareConnection(String url, String method) throws IOException {
        URL u = new URL(url);
        Log.d(TAG, "PREPARECONNECTION : URL[" + u + "]METHOD [" + method + "]");
        // trustAllHosts();
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        // c.setHostnameVerifier(new MyHostNameVerifier());

        c.setRequestMethod(method);
        c.setAllowUserInteraction(false);
        c.setUseCaches(false);
        c.setInstanceFollowRedirects(false);
        // c.setRequestProperty("User-Agent", USER_AGENT);

        // TODO : Check this !
        // c.setConnectTimeout(30000);
        // c.setReadTimeout(30000);
        return (c);
    }
}
